<?php

namespace App\Http\Middleware\Admin\v1;

use Closure;
use App\Exceptions\ApiException;
use App\Exceptions\ApiErrCode;
use App\Models\Customer;
use App\Services\Utils\ApiChecker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTGuard;

class CustomerAuth
{
    use ApiChecker;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->checkToken($request);

        /** @var JWTGuard $jwt */
        $jwt = Auth::guard(Customer::GUARD_NAME);

        /** @var User $admin */
        $admin = $jwt->user();

        if (! $admin) {
            throw new ApiException(ApiErrCode::JWT_TOKEN_INVALID, trans('middleware.token_invalid'));
        }
        return $next($request);
    }

    /**
     * @param Request $request
     *
     * @throws \Exception
     */
    private function checkToken(Request $request)
    {
        // if (config('admin.admin_debug')) return;
        
        $this->checkJwtTokenExist($request,trans('checker.check_jwt_token_exist'));
    }
}
